package mspdt.ontrade;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.Engine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.DelayModifier;
import org.andengine.entity.modifier.FadeInModifier;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.modifier.ParallelEntityModifier;
import org.andengine.entity.modifier.RotationByModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.scene.background.IBackground;
import org.andengine.entity.scene.background.SpriteBackground;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.opengl.texture.render.RenderTexture;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.BaseGameActivity;
import org.andengine.util.color.Color;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.IModifier;
import org.andengine.util.modifier.ease.EaseBackIn;
import org.andengine.util.modifier.ease.EaseBackInOut;
import org.andengine.util.modifier.ease.EaseBounceInOut;
import org.andengine.util.modifier.ease.EaseCircularInOut;
import org.andengine.util.modifier.ease.EaseCircularOut;
import org.andengine.util.modifier.ease.EaseQuadInOut;
import org.andengine.util.modifier.ease.EaseQuadOut;
import org.andengine.util.modifier.ease.EaseSineInOut;
import org.andengine.util.modifier.ease.EaseSineOut;
import org.andengine.util.modifier.ease.EaseStrongOut;

import android.app.AlertDialog;
import android.content.Intent;
import android.opengl.GLES20;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class Game1Activity extends BaseGameActivity implements IOnSceneTouchListener{

	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 720;
	private Camera mCamera;
	private Scene mainScene;// chooserScene;
	private Sprite bottle, back, arrow, info;
	private Sound sound_click, bottle_wheel;
	//private Sprite cycle;
	ArrayList<Sprite> bottles = new ArrayList<Sprite>();
	private boolean bottle_selected = false;

    private boolean mMotionStreaking = false;
	
	@Override
	public EngineOptions onCreateEngineOptions() {
		// TODO Auto-generated method stub
		mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		
		EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), mCamera);
		engineOptions.getAudioOptions().setNeedsSound(true);
		return engineOptions;
	}

//	@Override
//	public Engine onCreateEngine(EngineOptions pEngineOptions) {
//		return new Engine(pEngineOptions) {
//			private static final int RENDERTEXTURE_COUNT = 2;
//
//			private boolean mRenderTextureInitialized;
//
//			private final RenderTexture[] mRenderTextures = new RenderTexture[RENDERTEXTURE_COUNT];
//			private final Sprite[] mRenderTextureSprites = new Sprite[RENDERTEXTURE_COUNT];
//
//			private int mCurrentRenderTextureIndex = 0;
//
//			@Override
//			public void onDrawFrame(final GLState pGLState) throws InterruptedException {
//				final boolean firstFrame = !this.mRenderTextureInitialized;
//				if(firstFrame) {
//					this.initRenderTextures(pGLState);
//					this.mRenderTextureInitialized = true;
//				}
//
//				final int surfaceWidth = this.mCamera.getSurfaceWidth();
//				final int surfaceHeight = this.mCamera.getSurfaceHeight();
//
//				final int currentRenderTextureIndex = this.mCurrentRenderTextureIndex;
//				final int otherRenderTextureIndex = (currentRenderTextureIndex + 1) % RENDERTEXTURE_COUNT;
//
//				this.mRenderTextures[currentRenderTextureIndex].begin(pGLState, false, true);
//				{
//					/* Draw current frame. */
//					super.onDrawFrame(pGLState);
//
//					/* Draw previous frame with reduced alpha. */
//					if(!firstFrame) {
//						if(Game1Activity.this.mMotionStreaking) {
//							this.mRenderTextureSprites[otherRenderTextureIndex].setAlpha(0.9f);
//							this.mRenderTextureSprites[otherRenderTextureIndex].onDraw(pGLState, this.mCamera);
//						}
//					}
//				}
//				this.mRenderTextures[currentRenderTextureIndex].end(pGLState);
//
//				/* Draw combined frame with full alpha. */
//				{
//					pGLState.pushProjectionGLMatrix();
//					pGLState.orthoProjectionGLMatrixf(0, surfaceWidth, 0, surfaceHeight, -1, 1);
//					{
//						this.mRenderTextureSprites[otherRenderTextureIndex].setAlpha(1);
//						this.mRenderTextureSprites[otherRenderTextureIndex].onDraw(pGLState, this.mCamera);
//					}
//					pGLState.popProjectionGLMatrix();
//				}
//
//				/* Flip RenderTextures. */
//				this.mCurrentRenderTextureIndex = otherRenderTextureIndex;
//			}
//
//			private void initRenderTextures(final GLState pGLState) {
//				final int surfaceWidth = this.mCamera.getSurfaceWidth();
//				final int surfaceHeight = this.mCamera.getSurfaceHeight();
//
//				final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
//				for(int i = 0; i <= 1; i++) {
//					this.mRenderTextures[i] = new RenderTexture(Game1Activity.this.getTextureManager(), surfaceWidth, surfaceHeight);
//					this.mRenderTextures[i].init(pGLState);
//
//					final ITextureRegion renderTextureATextureRegion = TextureRegionFactory.extractFromTexture(this.mRenderTextures[i]);
//					this.mRenderTextureSprites[i] = new Sprite(0, 0, renderTextureATextureRegion, vertexBufferObjectManager);
//				}
//			}
//		};
//	}
	
	@Override
	public void onCreateResources(
			OnCreateResourcesCallback pOnCreateResourcesCallback)
			throws Exception {
		// TODO Auto-generated method stub
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("pic/");
//		BitmapTextureAtlas cycleTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 633, 633, TextureOptions.DEFAULT);
//		ITextureRegion cycleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(cycleTextureAtlas, this, "game1_cycle.png", 0, 0);
//		cycleTextureAtlas.load();
//		cycle = new Sprite(240-cycleTextureRegion.getHeight()/2, 360-cycleTextureRegion.getHeight()/2, 440, 440, cycleTextureRegion, mEngine.getVertexBufferObjectManager())
//		{
//			@Override
//			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
//				//if(devil!=Integer.parseInt(this.getUserData().toString()))
//					//this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
//				//male.clearEntityModifiers();
//				return true;
//			}
//		};
		BitmapTextureAtlas backTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 127, 127, TextureOptions.DEFAULT);
		ITextureRegion backTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(backTextureAtlas, this, "back.png", 0, 0);
		backTextureAtlas.load();
		back = new Sprite(20, -10, 80, 80, backTextureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					if(TouchEvent.ACTION_UP == pSceneTouchEvent.getAction())
					{
						this.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
							@Override
							public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
								Game1Activity.this.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										arrow.clearEntityModifiers();
										mainScene.detachChild(arrow);
										sound_click.play();
										//Toast.makeText(Game1Activity.this, "Sequence started.", Toast.LENGTH_SHORT).show();
									}
								});
							}

							@Override
							public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
								Game1Activity.this.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										mainScene.clearTouchAreas();
										mainScene.detachChildren();
										mainScene.clearUpdateHandlers();
										mEngine.stop();
										Game1Activity.this.finish();
									}
								});
							}
						}, new SequenceEntityModifier(new MoveModifier(0.6f, back.getX(), back.getX(), back.getY(), back.getY()-back.getHeight(), EaseBackInOut.getInstance()), new DelayModifier(0))));
					}
				return true;
			}
		};
		BitmapTextureAtlas arrowTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 100, 100, TextureOptions.DEFAULT);
		ITextureRegion arrowTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(arrowTextureAtlas, this, "arrow.png", 0, 0);
		arrowTextureAtlas.load();
		arrow = new Sprite(210, 330, 60, 60, arrowTextureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					//finish();
				return true;
			}
		};
		BitmapTextureAtlas infoAtlas = new BitmapTextureAtlas(this.getTextureManager(), 39, 39, TextureOptions.DEFAULT);
		ITextureRegion infoRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(infoAtlas, this, "help.png", 0, 0);
		infoAtlas.load();
		info = new Sprite(430, 670, 40, 40, infoRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if(pSceneTouchEvent.isActionUp())
				{
					final AlertDialog.Builder alert = new AlertDialog.Builder(Game1Activity.this);
					alert.setTitle(getResources().getString(R.string.info_title));
					alert.setMessage(getResources().getString(R.string.game1_info));
					//alert.show();
					Game1Activity.this.runOnUiThread(new Runnable() {
					    @Override
					    public void run() {
					    	alert.show();
//					    	Game1Activity.this.showDialog(MY_DIALOG_ID);
					    }
					});
				}
				return true;
			}
		};
		
		SoundFactory.setAssetBasePath("mfx/");
		try {
			this.sound_click = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "click.mp3");
			this.bottle_wheel = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "game2_bottle_wheel.mp3");
		} catch (final IOException e) {
			Debug.e(e);
		}
		
		pOnCreateResourcesCallback.onCreateResourcesFinished();
	}
	@Override
	public void onBackPressed()
	{
		back.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
			@Override
			public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
				Game1Activity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						sound_click.play();
					}
				});
			}
			@Override
			public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
				Game1Activity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mainScene.clearTouchAreas();
						mainScene.detachChildren();
						mainScene.clearUpdateHandlers();
						
						mEngine.stop();
						Game1Activity.this.finish();
					}
				});
			}
		}, new SequenceEntityModifier(new MoveModifier(0.6f, back.getX(), back.getX(), back.getY(), back.getY()-back.getHeight(), EaseBackInOut.getInstance()), new DelayModifier(0))));
	}
	public void onResume()
	{
		super.onResume();
		if(!mEngine.isRunning())
			mEngine.start();
	}
	@Override
	public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
			throws Exception {
		// TODO Auto-generated method stub
		
		BitmapTextureAtlas bgTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 768, 1024, TextureOptions.DEFAULT);
		ITextureRegion bgTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bgTextureAtlas, this, "game1_back.jpg", 0, 0);
		bgTextureAtlas.load();
		Sprite bgSprite = new Sprite(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, bgTextureRegion, mEngine.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				//if(devil!=Integer.parseInt(this.getUserData().toString()))
					//this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
				//male.clearEntityModifiers();
				return true;
			}
		};
		SpriteBackground bg = new SpriteBackground(bgSprite);
		mainScene = new Scene();
		mainScene.setBackground(bg);
		
		mainScene.setOnSceneTouchListener(this);
		mainScene.attachChild(back);
		mainScene.registerTouchArea(back);
		mainScene.attachChild(info);
		mainScene.registerTouchArea(info);
		//chooserScene = new Scene();
		//chooserScene.setBackground(new Background(0, 255, 50));
		
		
		String[] bottle_names = {"bottle1.png", "bottle2.png"};
		float[] bottlX = {65f, 255f};
		float[] bottlY = {130f, 130f};
		int[] bottlW = {179, 153};
		int[] bottlH = {506, 507};
		for(int i=0;i<bottle_names.length;i++)
		{
			BitmapTextureAtlas bottlesTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), bottlW[i], bottlH[i], TextureOptions.DEFAULT);
			ITextureRegion bottlesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bottlesTextureAtlas, this, bottle_names[i], 0, 0);
			bottlesTextureAtlas.load();
			Sprite bottl = new Sprite(0, 0, bottlW[i], bottlH[i], bottlesTextureRegion, mEngine.getVertexBufferObjectManager())
			{
				@Override
				public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					if(TouchEvent.ACTION_UP == pSceneTouchEvent.getAction())
					{
						this.registerEntityModifier(new SequenceEntityModifier(new MoveModifier(0.3f, this.getX(), (CAMERA_WIDTH - this.getWidth()) * 0.5f, this.getY(), (CAMERA_HEIGHT - this.getHeight()) * 0.5f)));
						bottle = this;
						bottle.setPosition((CAMERA_WIDTH - bottle.getWidth()) * 0.5f, (CAMERA_HEIGHT - bottle.getHeight()) * 0.5f);

						mainScene.clearTouchAreas();
						mainScene.detachChildren();
						mainScene.attachChild(back);
						mainScene.attachChild(bottle);
						mainScene.attachChild(info);
						mainScene.registerTouchArea(info);
						mainScene.registerTouchArea(back);
						
//						mainScene.attachChild(cycle);
						
						//mainScene.registerTouchArea(bottle);
						bottle_selected = true;
					}
						
					return true;
				}
			};
			bottl.setPosition(bottlX[i], bottlY[i]);
			bottl.setScale(0.7f);
			//bottl.setScaleX(1.2f);
			mainScene.attachChild(bottl);
			mainScene.registerTouchArea(bottl);
			
		}
		//chooserScene.setOnSceneTouchListener(Game1Activity.this);
		//mainScene.attachChild(chooserScene);
		//rotateBottle();
		pOnCreateSceneCallback.onCreateSceneFinished(this.mainScene);
	}


	public void rotateBottle()
	{
		bottle_wheel.play();
		bottle.clearEntityModifiers();
		//float start_rot = bottle.getRotation()%360;
		bottle.setRotation(bottle.getRotation()%360);
		float end_rot = 0f;
		Random rand = new Random();
		end_rot = rand.nextInt(360);
		//bottle.registerEntityModifier(new SequenceEntityModifier(new RotationModifier(15, start_rot, 1000*(end_rot+4), EaseStrongOut.getInstance()), new DelayModifier(2)));
		bottle.registerEntityModifier(new SequenceEntityModifier(new IEntityModifierListener() {
			@Override
			public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
				Game1Activity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						arrow.clearEntityModifiers();
						mainScene.detachChild(arrow);
						
						//Toast.makeText(Game1Activity.this, "Sequence started.", Toast.LENGTH_SHORT).show();
					}
				});
			}

			@Override
			public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
				Game1Activity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						float radius = 200f;
						float angle = bottle.getRotation()%360;
						float posX = (float)(radius*Math.cos((-90+angle)*(Math.PI/180)))+210;
				    	float poxY = (float)(radius*Math.sin((-90+angle)*(Math.PI/180)))+330;
						arrow.setPosition(posX, poxY);
						arrow.setRotation(angle);
						arrow.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.3f, 1f, 1.3f), new ScaleModifier(0.3f, 1.3f, 1f))));
						mainScene.attachChild(arrow);
						bottle_wheel.stop();
						//bottle.setRotation(bottle.getRotation()%360);
						//Toast.makeText(Game1Activity.this, "Sequence finished.", Toast.LENGTH_SHORT).show();
					}
				});
			}
		}, new SequenceEntityModifier(new RotationModifier(3, bottle.getRotation(), end_rot+7200, EaseCircularOut.getInstance()), new DelayModifier(0))));
		
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		if(bottle_selected && TouchEvent.ACTION_UP == pSceneTouchEvent.getAction())
			rotateBottle();
		return true;
	}

	@Override
	public void onPopulateScene(Scene pScene,
			OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
